var _contextPath;
$(document).ready(function() {
	_contextPath = $("#contextPath").val();
	merchantlist();
});

function getContextPath() {
	if ("" == _contextPath) {
		_contextPath = $("#contextPath").val();
	}
	return _contextPath;
}


var isNum = function(str) {
	return !isNaN($.trim(str));
};

var isInt = function(str) {
	return /^\d+$/.test(str);
};

var isDate = function(str) {
	return /^\d{2}[01]\d[0123]\d[012]\d[0123455]\d$/
			.test(str);
};

var isNull = function(str) {
	return $.trim(str) == "";
};

/**
 * 入库卡列表
 */
function merchantlist() {
	$(".merchantId").empty();
	$.ajax({
		type : 'POST',
		url : _contextPath + 'iccard/combocard/merchantlist',
		dataType : 'json',
		success : function(list) {
			if (list != null) {
				for ( var i = 0; i < list.length; i++) {
					var option = '<option value="' + list[i].merchantId
							+ '">编号：' + list[i].merchantCode +"  名称:"+ list[i].merchantName + '</option>';
					//$("#merchantId").append(option);
					$(".merchantId").each(function(index) {
						$(this).append(option);
						if ($("#comboCardId").val()){
							$(this).val($(this).attr("sval"));
						}
					});
				}
			}
		}
	});
}

function addm(){
	var length = $("#merctDiv .panel").size();
	var $cmtemp= $("#merctDiv .panel").first().clone(true,true);
	$cmtemp.find(":input").removeClass("validatebox-invalid");
	$("strong",$cmtemp).html(length+1);
	$("select,input",$cmtemp).val("");
	$("select,input",$cmtemp).each(function(index) { 
		if(index==0){
			$(this).attr("name","comboCardProductDetails["+length+"].merchantId");
		}else if(index==1){
			$(this).attr("name","comboCardProductDetails["+length+"].productNames");
		}else if(index==2){
			$(this).attr("name","comboCardProductDetails["+length+"].productOrignalPrice");
			$(this).attr("validType","checkyjg["+length+"]");
		}else if(index==3){
			$(this).attr("name","comboCardProductDetails["+length+"].productFavorablePrice");
			$(this).attr("validType","checkyhjg["+length+"]");
		}else if(index==4){
			$(this).attr("name","comboCardProductDetails["+length+"].productSalePrice");
			$(this).attr("validType","checkxsjg["+length+"]");
		}else if(index==5){
			$(this).attr("name","comboCardProductDetails["+length+"].productCopies");
		}else if(index==6){
			$(this).attr("name","comboCardProductDetails["+length+"].productRaisePriceRate");
		}else if(index==7){
			$(this).attr("name","comboCardProductDetails["+length+"].comboCardProductDetailId");
		}
		$("select[name='comboCardProductDetails["+index+"].merchantId']").val($("select[name='comboCardProductDetails[0].merchantId']").val());
	});
	$("#merctDiv").append($cmtemp);
	$.parser.parse("#merctDiv");
}
var replaceAll = function(s1,s2) { 
    return this.replace(new RegExp("\"","gm")); 
}



function delm(obj){
	var length = $("#merctDiv .panel").size();
	if(length>1){
//		top.confirm("你确定要删除选择商户信息吗？", function() {
		console.info($(obj).parents("tr").parent().parent().parent().parent());
		$(obj).parents("tr").parent().parent().parent().parent().remove();
		$("#merctDiv .panel").each(function(i) {
			$("strong",$(this)).html(i+1);
			$("select,input",$(this)).each(function(index) { 
				if(index==0){
					$(this).attr("name","comboCardProductDetails["+i+"].merchantId");
				}else if(index==1){
					$(this).attr("name","comboCardProductDetails["+i+"].productNames");
				}else if(index==2){
					$(this).attr("name","comboCardProductDetails["+i+"].productOrignalPrice");
					$(this).attr("validType","checkyjg["+i+"]");
				}else if(index==3){
					$(this).attr("name","comboCardProductDetails["+i+"].productFavorablePrice");
					$(this).attr("validType","checkyhjg["+i+"]");
				}else if(index==4){
					$(this).attr("name","comboCardProductDetails["+i+"].productSalePrice");
					$(this).attr("validType","checkxsjg["+i+"]");
				}else if(index==5){
					$(this).attr("name","comboCardProductDetails["+i+"].productCopies");
				}else if(index==6){
					$(this).attr("name","comboCardProductDetails["+i+"].productRaisePriceRate");
				}else if(index==7){
					$(this).attr("name","comboCardProductDetails["+i+"].comboCardProductDetailId");
				}
			})
		});
		merchantChange(obj);
//		});
	}else{
		top.uppShow("至少保证有一个商家参加套餐");
	}
}

function saveCombo() {
	var begintime =$("input[name='begintime']").val();
	var endtime =$("input[name='endtime']").val();
	if(begintime <= endtime){
		$("#savab").attr('disabled', 'disabled');
		_contextPath =$("#contextPath").val();
		if ($("#comboCardId").val())
			url = _contextPath + "iccard/combocard/update?rid=" + Math.random();
		else {
			url = _contextPath + "iccard/combocard/add?rid=" + Math.random();
		}
		var data = $("#combocard_form").serializeArray();
		if (!$("#combocard_form").form('validate')){
			return false;
		}
		$('table input,textarea').attr('disabled', 'disabled');
		$.ajax({
			type : 'POST',
			url : url,
			data : data,
			dataType : 'json',
			success : function(root) {
				top.uppShow(root.msgDesc);
				// 隐藏保存按钮
				$("#btn_div").hide();
				window.top.reload_combocard_list.call();
				window.top.closeCurrentTab(window.parent.getCurrentTagTitle());
			},
			error : function(data) {
				uppAjaxError(data);
				$("#savab").attr('disabled', '');
			}
		});
	}else{
		top.uppShow("结束时间不能小于开始时间");
	}
}

function clearForm(){  
    $('#combocard_form').form('clear');  
}


function merchantChange(obj){
	if(isNum($(obj).val())){
		var yj = parseFloat($("input",$(obj).parents("table")).eq(1).val());
		var yh = parseFloat($("input",$(obj).parents("table")).eq(2).val());
		var xs = parseFloat($("input",$(obj).parents("table")).eq(3).val());
		
		var zfs=0;
		$("input[name*='productCopies']").each(function(index) { 
			if($(this).val()==""){
				return ;
			}else{
				if(parseInt($(this).val())<zfs || zfs==0){
					zfs = parseInt($(this).val());
				}
			}
		});
		if(isNum(zfs)){
			$("#comboCardTotalCopies").val(zfs);
		}
		
		if(isNum(yh) && xs!=0 && yh!=0){
			var jabfb = (xs-yh)/yh;
			if(isNum(jabfb)){
				$("input",$(obj).parents("table")).eq(5).val(Percentage(jabfb));
			}
		}
		
		var yzjg=0;
		$("input[name*='productOrignalPrice']").each(function(index) { 
			if($(this).val()==""){
				return ;
			}else{
				yzjg = yzjg+parseFloat($(this).val());
			}
		});
		if(isNum(yzjg)){
			$("#comboCardOrignalPrice").val(yzjg);
		}
		
		var zyhjg=0;
		$("input[name*='productFavorablePrice']").each(function(index) { 
			if($(this).val()==""){
				return ;
			}else{
				zyhjg = zyhjg+parseFloat($(this).val());
			}
		});
		if(isNum(zyhjg)){
			$("#comboCardFavorablePrice").val(zyhjg);
		}
		
		var zxsjg=0;
		$("input[name*='productSalePrice']").each(function(index) { 
			if($(this).val()==""){
				return ;
			}else{
				zxsjg = zxsjg+parseFloat($(this).val());
			}
		});
		if(isNum(zxsjg)){
			$("#comboCardSalePrice").val(zxsjg);
		}
		
		if(isNum(zyhjg) && zyhjg!=0 && zxsjg!=0){
			var zjabfb = (zxsjg-zyhjg)/zyhjg;
			if(isNum(zjabfb)){
				$("#comboCardRaisePriceRate").val(Percentage(zjabfb));
			}
		}
		
		if(isNum(yzjg) && yzjg!=0 && zxsjg!=0){
			var zjk = zxsjg/yzjg;
			if(isNum(zjk)){
				$("#totalDiscount").val(Percentage(zjk));
			}
		}
		
	}
}

function Percentage(num) {
    return (Math.round(num * 10000) / 100.00); 小数点后两位百分比
}

$.extend($.fn.validatebox.defaults.rules, {
    number: {
        validator: function (value, param) {
            return /^\d+$/.test(value);
        },
        message: '请输入数字'
    },positiveInt: {// 正整数
        validator: function (value) {
            return /^[0-9]*[1-9][0-9]*$/.test(value);
        },
        message: '请输入正整数，并确保格式正确'
    },intOrFloat: {// 验证整数或小数
        validator: function (value) {
            return /^\d+(\.\d+)?$/i.test(value);
        },
        message: '请输入数字，并确保格式正确'
    },minLength: {
        validator: function (value, param) {
            return value.length >= param[0];
        },
        message: '请输入至少（2）个字符.'
    },checkCardName : {  
        validator : function(value) {
        	var bl;
            $.ajax({
                async : false,  
                type : 'post',  
                url : _contextPath+'iccard/combocard/checkCardName',  
                data : {  
                    'cardName' : value
                },  
                success : function(date) {
                    if ((date == 'true' || date) && $.trim(value)!=$("#oldcomboCardName").val()) {
                    	bl= false;  
                    }else{
                    	bl= true;
                    }
                }  
            });  
            return bl;  
        },  
        message : '您输入的套餐名称已存在！'  
    },checkyhjg: {  
        validator: function (value, param) {
        	if (param != undefined) {
        		var yjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productOrignalPrice']").val());
        		var yhjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productFavorablePrice']").val());
        		var xsjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productSalePrice']").val());
        		if(yjg!='' && yhjg>yjg){
        			$.fn.validatebox.defaults.rules.checkyhjg.message = '优惠价格不能大于原价格'; 
                    return false;
        		}
        		if(xsjg!='' && yhjg>xsjg){
        			$.fn.validatebox.defaults.rules.checkyhjg.message = '优惠价格不能大于销售价格'; 
                    return false;
        		}
            }
        	if(!/^\d+(\.\d+)?$/i.test(value)){
        		$.fn.validatebox.defaults.rules.checkyhjg.message = '请输入数字，并确保格式正确'; 
                return false;
            }
        	return true;
        },  
        message: '请输入数字，并确保格式正确'  
    },checkxsjg: {  
        validator: function (value, param) {  
        	if (param != undefined) {
        		var yjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productOrignalPrice']").val());
        		var yhjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productFavorablePrice']").val());
        		var xsjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productSalePrice']").val());
        		if(yjg!='' && xsjg>yjg){
        			$.fn.validatebox.defaults.rules.checkxsjg.message = '销售价格不能大于原价格'; 
                    return false;
        		}
        		if(yhjg!='' && xsjg<yhjg){
        			$.fn.validatebox.defaults.rules.checkxsjg.message = '销售价格不能小于优惠价格'; 
                    return false;
        		}
            }
        	if(!/^\d+(\.\d+)?$/i.test(value)){
        		$.fn.validatebox.defaults.rules.checkxsjg.message = '请输入数字，并确保格式正确'; 
                return false;
            }
        	return true;
        },  
        message: '请输入数字，并确保格式正确'  
    },checkyjg: {  
        validator: function (value, param) {  
        	if (param != undefined) {
        		var yjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productOrignalPrice']").val());
        		var yhjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productFavorablePrice']").val());
        		var xsjg = parseFloat($("input[name='comboCardProductDetails["+param[0]+"].productSalePrice']").val());
        		if(xsjg!='' && yjg>xsjg){
        			$.fn.validatebox.defaults.rules.checkyjg.message = '原价格不能小于销售价格'; 
                    return false;
        		}
        		if(xsjg!='' && yjg>yhjg){
        			$.fn.validatebox.defaults.rules.checkyjg.message = '原价格不能小于优惠价格'; 
                    return false;
        		}
            }
        	if(!/^\d+(\.\d+)?$/i.test(value)){
        		$.fn.validatebox.defaults.rules.checkyjg.message = '请输入数字，并确保格式正确'; 
                return false;
            }
        	return true;
        },  
        message: '请输入数字，并确保格式正确'  
    },jabfb: {
        validator: function (value) {
            return value>0;
        },
        message: '加价百分比必须为正数'
    }
});

function back(){
	window.top.reload_combocard_list.call();
	window.top.closeCurrentTab(window.parent.getCurrentTagTitle());
}